from django import forms
from django.db import IntegrityError
from django.http import JsonResponse
from django.views.generic import View

from main.decorators import validate_input
from main.models import User
from main.responses import *


class Users(View):
    post_dict = {
        'order': forms.IntegerField(required=False, min_value=0, max_value=3),
        'username': forms.CharField(),
    }
    available_orders = [
        'create_time', '-create_time',
        'name', '-name',
    ]

    @validate_input(post_dict)
    def post(self, request, username, order=1):
        """
        登录，若用户不存在则注册新用户并登录

        :param order: 排序方式
            0: 注册时间升序
            1: 注册时间降序（默认值）
            2: 昵称升序
            3: 昵称降序
        :param username: 用户名
        :return: 200 | 400
            id: 用户ID
            count: 用户关注的公众号总数
            list: 公众号列表
                id: 公众号ID
                name: 公众号名称
                owner_id: 所有者ID
                create_time: 公众号注册时间
        """
        k = self.available_orders[order]

        try:
            user = User.enabled.create_user(username)
            c = 0
            l = []
            return JsonResponse({'id': user.id, 'count': c, 'list': l})
        except ValueError as e:
            return Http400(e)
        except IntegrityError:
            user = User.enabled.get(username=username)
            c = user.subscriptions.count()
            subs = user.subscriptions.all().order_by(k)

            l = [{'id': s.subscription.id,
                  'name': s.subscription.name,
                  'create_time': s.subscription.create_time} for s in subs]
            return JsonResponse({'id': user.id, 'count': c, 'list': l})

